package com.qiandw.common.cassandra

import java.util.function.Consumer

import com.datastax.driver.core.ColumnDefinitions.Definition
import com.datastax.driver.core.{ResultSet, Row, Statement}
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
  * Created by Administrator on 2016/12/21.
  */
@Component
class CassandraDaoSrvImpl extends AbstractCassandraDao with CassandraDaoSrv {

  @Autowired
  var jsonMapper: ObjectMapper = _

  override def Execute(cql: String): ResultSet = Session.execute(cql)

  override def executeAndPrintAsJson(statement: Statement): String = {
    val results = new java.util.LinkedList[java.util.Map[String, Object]]
    Session.execute(statement).all().forEach(new Consumer[Row] {
      override def accept(r: Row): Unit = {
        val colMap = new java.util.HashMap[String, Object]
        results.add(colMap)
        r.getColumnDefinitions.forEach(new Consumer[Definition] {
          override def accept(cd: Definition): Unit = {
            colMap.put(cd.getName, r.getObject(cd.getName))
          }
        })
      }
    })
    jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(results)
  }
}
